package com.aiti.lulian.controller.lulian;


import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.obj.BeanCopyUtil;
import com.aiti.lulian.dto.LuLianPurchaseDemandDto;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.LuLianPurchaseDemand;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ILuLianPurchaseDemandService;
import com.aiti.lulian.vo.LuLianPurchaseDemandVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("LuLianPurchaseDemand")
@Api(tags = " LuLianPurchaseDemand", description = "采购需求")
public class LuLianPurchaseDemandController extends WebController {
    protected final Logger logger = LoggerFactory.getLogger(LuLianPurchaseDemandController.class);


    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;

    @Autowired
    private ILuLianPurchaseDemandService purchaseDemandService;

    @ApiOperation(value = "新增采购需求")
    @PostMapping("add")
    public Message save(@RequestBody LuLianPurchaseDemandDto purchaseDemandDto) {
        try {
            if (purchaseDemandDto == null) {
                logger.error("新增异常：===》入参异常");
                return Message.fail("入参异常");
            }
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterprise> enterpriseHistoryWrapper = new LambdaQueryWrapper<>();
            enterpriseHistoryWrapper.in(LuLianEnterprise::getBaseId, enterpriseIds);
            int count = luLianEnterpriseService.count(enterpriseHistoryWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            }
            //新增采购需求
            purchaseDemandDto.setCreator(userId);
            LuLianPurchaseDemand luLianPurchaseDemand = BeanCopyUtil.convertBean(purchaseDemandDto, LuLianPurchaseDemand.class);
//            luLianPurchaseDemand.setBaseCreateTime();
            return Success(purchaseDemandService.save(luLianPurchaseDemand));
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "采购需求列表-分页")
    @GetMapping("list")
    public Message findLuLianPurchaseDemandListPage(LuLianPurchaseDemandDto luLianPurchaseDemandDto) {
        try {
            Integer pageSize = luLianPurchaseDemandDto.getPageSize();
            Integer pageNum = luLianPurchaseDemandDto.getPageNum();
            Page<LuLianPurchaseDemand> page = startPage(pageNum, pageSize);
            List<LuLianPurchaseDemandVo> list = purchaseDemandService.findLuLianPurchaseDemandListPage(page, luLianPurchaseDemandDto);
            return Success(getPageResult(list, pageNum, pageSize, (int) page.getTotal()));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }



    //采购需求详情、回显
    @ApiOperation(value = "采购需求详情")
    @GetMapping("detail")
    public Message findLuLianPurchaseDemandDetail(String baseId) {
        try {
            LuLianPurchaseDemandVo purchaseDemand = purchaseDemandService.selectById(baseId);
            if (purchaseDemand == null) {
                return Fail("采购需求不存在！");
            }
            return Success(purchaseDemand);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    //采购需求修改
    @ApiOperation(value = "采购需求修改")
    @PostMapping("update")
    public Message updateLuLianPurchaseDemand(@RequestBody LuLianPurchaseDemandDto purchaseDemandDto) {
        try {
            if (purchaseDemandDto == null) {
                logger.error("修改异常：===》入参异常");
                return Message.fail("入参异常");
            }
            LuLianPurchaseDemand purchaseDemand = purchaseDemandService.getById(purchaseDemandDto.getBaseId());
            if (purchaseDemand == null) {
                return Fail("采购需求不存在！");
            }
            BeanUtils.copyProperties(purchaseDemand, purchaseDemandDto);
            purchaseDemandService.updateById(purchaseDemand);
            return Success();
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Error(e.getMessage());
        }
    }


    //根据当前登录用户查找他的企业信息
    @GetMapping("findEnterpriseByUserId")
    public Message findEnterpriseByUserId() {
        try {    //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录-");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            if (enterpriseUserList == null || enterpriseUserList.size() == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (enterpriseUserList.size() > 1) {
                return Fail("该账号关联了多个认证企业！");
            }
            String enterpriseId = enterpriseUserList.get(0).getEnterpriseId();
            LuLianEnterprise enterprise = luLianEnterpriseService.getById(enterpriseId);
            if (enterprise == null) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            }
            return Success(enterprise);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }
}
